//
//  AppDelegate.swift
//  sina
//
//  Created by DXapple on 15/11/8.
//  Copyright © 2015年 sqlite. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        let account = UserAccount.loadAccount()
        print(account)
        // Override point for customization after application launch.
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        
        window?.backgroundColor = UIColor.whiteColor()
        
        window?.makeKeyAndVisible()
        //设置跟控制器
        window?.rootViewController = defaultRootController()
        //注册通知
        registerNotification()
        //主题颜色
        setThemeColor()
        
        return true
    }
    private func registerNotification() {
        //object  观测某个对象发出的通知 如果为nil  就是观测所有的对象发出的通知

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchToRootVC:", name: AppSwitchRootViewControler, object: nil)
    
    }
    @objc private func switchToRootVC(n: NSNotification) {
        //如果没登陆了 先进入main 登陆
        if (n.object as? String ) != nil {

        window?.rootViewController = WelComeViewController()
            return
        }
        //如果登陆了直接到main
    window?.rootViewController = MainViewController()
    
    }
    
    
    //判断是否登陆
    private func defaultRootController() -> UIViewController {
    //是否登陆
        if UserAccountViewModel().userLogin {
    // 是否是新版本
            return isNewVersion() ? NewFeatureViewController() : WelComeViewController()
        }
    return MainViewController()
    }
    
    
    
    
    
    
    private func setThemeColor() {
    //设置根控制器的默认颜色   和每一个 tabbar的颜色
    UINavigationBar.appearance().tintColor = themeColor
        UITabBar.appearance().tintColor = themeColor
    
    }
    private func isNewVersion() -> Bool{
    //获取现在版本
    let version = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
    let versionNum = Double(version)
        //获取旧版一般存在沙盒
    
        let key = "sanBoxKey"
        let userdefaults = NSUserDefaults.standardUserDefaults()
        let lastVersion = userdefaults.doubleForKey(key)
        print(lastVersion)
        
    userdefaults.setDouble (versionNum!, forKey: key)
        userdefaults.synchronize()
        //比较新旧版本

        return versionNum! > lastVersion
    }
    
    
    
  }

